package com.example.demo.control;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.confi.JenkinsConf;
import com.example.demo.others.git.*;
import com.example.demo.others.jenkins.Jenkins;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017-6-9.
 */
@RestController
public class JenkinsControl {

    Logger logger = LoggerFactory.getLogger(JenkinsControl.class);

    @Autowired
    AutoPushDaily autoPushDaily;
    @Autowired
    AutoPushRC autoPushRC;
    @Autowired
    AutoPushOnline autoPushOnline;


    /**
     * restart
     *
     * @return
     */
    @RequestMapping("/jenkins/redeploy")

    public String restart(String dev, String file, HttpServletRequest request) {
        JSONObject j = new JSONObject();

        List<JSONObject> res = new ArrayList<>();
        if (LoginUtil.valid(request)) return "redirect:/tologin";

        String jenname = SessionUtil.jenkinsname(request);
        String gitname = SessionUtil.gitname(request);
        try {

            deploy(dev, file, jenname);
            return "success";
        } catch (Exception e) {
            return e.getMessage();
        }


    }

    public static void deploy(String dev,
                              String file, String jenname) {
        Map<String, String> params = new HashMap<>();
        params.put("key", "action,test_ip");
        params.put("val", "deploy,");
        if (dev.equals("daily")) {
            JenkinsConf.list.forEach(m -> {
                if (m.getString("file").equals(file)) {
                    String daily_deploy = m.getString("daily_deploy");
                    if (StringUtils.isNotBlank(daily_deploy)) {
                        params.put("val", "deploy," + m.getString("test_ip"));
                        Jenkins.deploy(jenname, daily_deploy, params);
                    }
                }
            });
        }
    }

    /**
     * 触发Jenkins 打包
     *
     * @param v
     * @param dev
     * @param msg
     * @param pak
     * @param file
     * @param request
     * @param branch
     * @param sub_module
     * @param clean
     * @return
     */
    @RequestMapping("/jenkins/package")

    public String da(Model v, String dev, String msg, String pak
            , String file, HttpServletRequest request, String branch, String sub_module, String clean) {

        if (StringUtils.isBlank(branch)) {
            if (dev.equals("daily")) {
                branch = "origin/develop";
            } else if (dev.equals("online") || dev.equals("rc")) {
                branch = "origin/master";
            }

        }
        List<JSONObject> res = new ArrayList<>();
        if (LoginUtil.valid(request)) return "redirect:/tologin";
        String jenname = SessionUtil.jenkinsname(request);
        Map<String, String> params = new HashMap<>();

        params.put("key", "branch,sub_module");
        params.put("val", branch);
        params.put("clean", clean);
        JenkinsConf.list.forEach(j -> {
            if (j.getString("file").equals(file)) {

                String sub_model = j.getString("sub_model");
                if (StringUtils.isNotBlank(sub_model)) {
                    params.put("val", params.get("val") + "," + sub_model);
                }
                int pub = j.getIntValue("pub");
                params.put("clean", j.getString("clean"));

                if (pub == 1) {
                    params.put("clean", "true");
                }
            }
        });


        List<String> ms = Jenkins.dabao(jenname, file, params);


        logger.info("index dev:{}, msg:{}", dev, msg);

        JSONObject j = new JSONObject();
        j.put("env", dev);

        j.put("res", res);
        j.put("msg", ms);


        return j.toJSONString();


    }


    /**
     * ios push 证书
     *
     * @param dev
     * @return
     */
    @RequestMapping("/git/crts")

    public String crts(String dev ,HttpServletRequest request) {
        List<JSONObject> res = new ArrayList<>();


        if (LoginUtil.valid(request)) return "redirect:/tologin";

        String jenname = SessionUtil.jenkinsname(request);
        String gitname = SessionUtil.gitname(request);
        if (dev.equals("daily")) {

            IosTst.run();

        } else if (dev.equals("online")) {
            IosPrd.run();
        }
        JSONObject j = new JSONObject();
        j.put("env", dev);
        j.put("res", res);
        return j.toJSONString();
    }


    /**
     * download push deploy
     *
     * @return
     */
    @RequestMapping("/git/download_push_deploy")

    public String index(Model v,  String dev,   String msg,
                        String file, HttpServletRequest request ) {
        if (StringUtils.isBlank(msg))
            return "push message 不能为空";
        JSONObject j = new JSONObject();

        List<JSONObject> res = new ArrayList<>();
        if (LoginUtil.valid(request)) return "redirect:/tologin";

        String jenname = SessionUtil.jenkinsname(request);
        String gitname = SessionUtil.gitname(request);
        try {
            com.example.demo.others.jenkins.Jenkins.run(jenname, file);
            if (dev.equals("daily")) {
                res = autoPushDaily.run(gitname, msg, file);
            } else if (dev.equals("rc")) {
                res = autoPushRC.run(gitname, msg, file);
            } else if (dev.equals("online")) {
                res = autoPushOnline.run(gitname, msg, file);
            }
            logger.info("index dev:{}, msg:{}", dev, msg);
            j.put("env", dev);
            j.put("res", res);
            JenkinsControl.deploy(dev, file, jenname);
        } catch (Exception e) {
            return e.getMessage();
        }
        return j.toJSONString();


    }


}
